﻿using System.ComponentModel;
using System.Windows;
using WikiUploader.Classes;

namespace WikiUploader
{
   /// <summary>
   /// Interaction logic for MainWindow.xaml
   /// </summary>
   public partial class MainWindow
   {
      public MainWindow ()
      {
         InitializeComponent ();
         var viewModel = (MainViewModel)this.DataContext;
         viewModel.PropertyChanged += ViewModelPropertyChanged;
         if (!string.IsNullOrEmpty (viewModel.Password))
            this._Password.Password = viewModel.Password;
         this._Password.PasswordChanged += PasswordChanged;
      }

      private void ViewModelPropertyChanged (object sender, PropertyChangedEventArgs e)
      {
         if (e.PropertyName == "Password")
         {
            this._Password.PasswordChanged -= PasswordChanged;
            var viewModel = (MainViewModel) this.DataContext;
            this._Password.Password = viewModel.Password;
            this._Password.PasswordChanged += PasswordChanged;
         }
      }

      private void PasswordChanged (object sender, RoutedEventArgs e)
      {
         var viewModel = (MainViewModel) this.DataContext;
         viewModel.Password = this._Password.Password;
      }

      private void WindowClosing (object sender, CancelEventArgs e)
      {
         var viewModel = (MainViewModel)this.DataContext;
         viewModel.PropertyChanged -= ViewModelPropertyChanged;
         this._Password.PasswordChanged -= PasswordChanged;
         viewModel.Closing ();
      }
   }
}
